package com.wushi.lenovo.asia5b.app_di.login.presenter;

import com.example.umeng_sdk.ThirdInfoModel;
import com.mvp.base.BasePresenter;
import com.mvp.base.model.ResultModel;
import com.mvp.helper.WCallBack;
import com.mvp.networking.CustomThrowable;
import com.mvp.utils.ToastUtil;
import com.mvp.utils.https.MapHelper;
import com.wushi.lenovo.asia5b.app_config.CommonConstant;
import com.wushi.lenovo.asia5b.app_config.UserRepository;
import com.wushi.lenovo.asia5b.app_di.login.mvpview.LoginThridActivityView;
import com.wushi.lenovo.asia5b.app_event.LoginEvent;
import com.wushi.lenovo.asia5b.app_http.ApiService;
import com.wushi.lenovo.asia5b.app_model.other.CacheType;
import com.wushi.lenovo.asia5b.app_model.other.UserInfo;
import com.wushi.lenovo.asia5b.app_model.profile.CountryModel;
import com.wushi.lenovo.asia5b.app_model.result.LoginResModel;
import com.wushi.lenovo.asia5b.app_push.PushHelper;
import com.wushi.lenovo.asia5b.app_utils.SystemUtil;
import com.wushi.lenovo.asia5b.app_utils.helper.CacheHelper;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

/**
 * Created by zhangyuncai on 2018/11/29.
 */
public class LoginThridActivityPresenter extends BasePresenter<LoginThridActivityView> {

    ApiService apiService;

    @Inject
    public LoginThridActivityPresenter(ApiService apiService) {
        this.apiService = apiService;
    }

    public void login(ThirdInfoModel infoModel) {
        Map<String, Object> map = MapHelper.newHashMap();
        if (infoModel.getPlatform() != ThirdInfoModel.SHARE_MEDIA.WEIXIN) {
            map.put("email", infoModel.getEmail());
        }
        map.put("third_id", infoModel.getUid());
        map.put("type", infoModel.getPlatform() == ThirdInfoModel.SHARE_MEDIA.WEIXIN ? "wechat" : "facebook");
        map.put("app_register_id", PushHelper.getRegistrationId());
        map.put("app_os", "1");
        SystemUtil.addSystemParam(map);
        baseSubscribe(getUserInfoObservable(apiService.loginThird(map), infoModel),
                userInfoResultModel -> {
                    loginResult(userInfoResultModel);
                });
    }

    //获取国家列表
    public void getCountrys() {
        CacheHelper.getCountrys(new WCallBack<List<CountryModel>>() {
            @Override
            public void callback(List<CountryModel> countryModels) {
                getView().getCountrysResult(countryModels);
            }
        }, CacheType.LOCAL);
//        baseSubscribe(apiService.getCountrys(),
//                newTransfomer().setToastError(false).setShowLoading(false).setDissLoading(false)
//                , listResultModel -> {
//                    getView().getCountrysResult(listResultModel.getData());
//                });
    }


    private void loginResult(ResultModel<UserInfo> userInfoResultModel) {
        if (userInfoResultModel.isSuccess() && userInfoResultModel.getData() != null) {
            UserRepository.setUserInfo(userInfoResultModel.getData());
            EventBus.getDefault().post(new LoginEvent(CommonConstant.LOGIN_SUCCESS));
            ToastUtil.showToast(userInfoResultModel.getMsg());
        }
        getView().loginResult(userInfoResultModel.isSuccess());
    }

    private Observable<ResultModel<UserInfo>> getUserInfoObservable(Observable<ResultModel<LoginResModel>> observable, ThirdInfoModel infoModel) {
        return observable.flatMap(new Function<ResultModel<LoginResModel>, ObservableSource<ResultModel<UserInfo>>>() {
            @Override
            public ObservableSource<ResultModel<UserInfo>> apply(ResultModel<LoginResModel> loginResModelResultModel) throws Exception {
                if (loginResModelResultModel.isSuccess()) {//todo 这里只是表示访问接口成功,不一定表示登录成功
                    final LoginResModel loginResModel = loginResModelResultModel.getData();
                    if (loginResModel == null && infoModel.getPlatform() == ThirdInfoModel.SHARE_MEDIA.FACEBOOK) {//facebook资料不齐
                        getView().facebookLoginError(infoModel);
                    }
                    /*
                    todo 微信登录失败案例
                    {"headers": {}, "original": {"msg": "wechat haven't bind with email.", "data": [], "result": 1}, "exception": null}
                     */
                    if (loginResModel == null) {
                        return Observable.error(new CustomThrowable(loginResModelResultModel.getMsg()));
                    }
                    return apiService.getUserInfo(loginResModel.getMemberId()).map(new Function<ResultModel<UserInfo>, ResultModel<UserInfo>>() {
                        @Override
                        public ResultModel<UserInfo> apply(ResultModel<UserInfo> userInfoResultModel) throws Exception {
                            if (userInfoResultModel.isSuccess() && userInfoResultModel.getData() != null) {
                                //保存userToken
                                userInfoResultModel.getData().setUserToken(loginResModel.getAccess_token());
                            }
                            return userInfoResultModel;
                        }
                    });
                }
                return Observable.error(new CustomThrowable(loginResModelResultModel.getMsg()));
            }
        });
    }
}